package org.dbunit.operation;

import java.util.BitSet;

import org.dbunit.DatabaseUnitException;
import org.dbunit.database.IDatabaseConnection;
import org.dbunit.dataset.Column;
import org.dbunit.dataset.DataSetException;
import org.dbunit.dataset.IDataSet;
import org.dbunit.dataset.ITableIterator;
import org.dbunit.dataset.ITableMetaData;
import org.dbunit.dataset.NoPrimaryKeyException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class RuleProjectDeleteOperation extends AbstractBatchOperation{

	    /**
	     * Logger for this class
	     */
	    private static final Logger logger = LoggerFactory.getLogger(DeleteOperation.class);

	    public RuleProjectDeleteOperation()
	    {
	        _reverseRowOrder = true;
	    }

	    ////////////////////////////////////////////////////////////////////////////
	    // AbstractBatchOperation class

	    protected ITableIterator iterator(IDataSet dataSet) throws DatabaseUnitException
	    {
	        logger.debug("iterator(dataSet={}) - start", dataSet);
	        return dataSet.reverseIterator();
	    }

	    public OperationData getOperationData(ITableMetaData metaData, BitSet ignoreMapping, IDatabaseConnection connection) throws DataSetException
	    {
	    	if (logger.isDebugEnabled())
	    	{
	    		logger.debug("getOperationData(metaData={}, ignoreMapping={}, connection={}) - start",
	    				new Object[]{ metaData, ignoreMapping, connection });
	    	}

	        Column[] cols = metaData.getColumns();
	        Column projectCode = null;
	        for(Column col:cols){
	        	if("PROJECT_CODE".equalsIgnoreCase(col.getColumnName())||"PROJECTCODE".equalsIgnoreCase(col.getColumnName())){
	        		projectCode = col;
	        	}
	        }
	        //没有projectCode，根据主键删除
	        if(projectCode == null){
	        	Column[] primaryKeys = metaData.getPrimaryKeys();
	            if (primaryKeys.length == 0)
	            {
	                throw new NoPrimaryKeyException(metaData.getTableName());
	            }

	            // delete from
	            StringBuffer sqlBuffer = new StringBuffer(128);
	            sqlBuffer.append("delete from ");
	            sqlBuffer.append(getQualifiedName(connection.getSchema(),
	                    metaData.getTableName(), connection));

	            // where
	            sqlBuffer.append(" where ");
	            for (int i = 0; i < primaryKeys.length; i++)
	            {
	                // escape column name
	                String columnName = getQualifiedName(null,
	                        primaryKeys[i].getColumnName(), connection);
	                sqlBuffer.append(columnName);

	                sqlBuffer.append(" = ?");
	                if (i + 1 < primaryKeys.length)
	                {
	                    sqlBuffer.append(" and ");
	                }
	            }

	            return new OperationData(sqlBuffer.toString(), primaryKeys);
	        }

	        // 根据projectCode删除
	        StringBuffer sqlBuffer = new StringBuffer(128);
	        sqlBuffer.append("delete from ");
	        sqlBuffer.append(getQualifiedName(connection.getSchema(),
	                metaData.getTableName(), connection));

	        // where
	        sqlBuffer.append(" where ").append(projectCode.getColumnName()).append(" = ?");


	        return new OperationData(sqlBuffer.toString(), new Column[]{projectCode});
	    }

	}

